package com.terabits.smartriver.util;

import com.terabits.smartriver.netty.protocol.AuthMessage;
import com.terabits.smartriver.netty.protocol.Type;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;

import java.lang.reflect.Array;

public class PacketUtil {

    /**
     * Purpose:验证帧头 并将十六进制转换而来的byte[]数据转换成十进制数据返回
     *
     * @param buffer
     * @return
     * @throws DecoderException
     */
    public static short[] verify(byte[] buffer) throws DecoderException {

        short[] buff = new short[buffer.length];
        for (int i = 0; i < buffer.length; i++) {
            buff[i] = (short) (Array.getShort(buffer, i) & 0xff);
        }

        String a = toStringHex(buff);
        System.out.println(a.substring(a.length() - 4));
//        System.out.println(CRC16.check(a.substring(4, a.length() - 4)));
        /* 判断包头 长度 以及CRC校验码 是否正确 */
        if (buff[0] == 90 && buff[1] == 165 && ((Integer.valueOf("" + buff[2]).equals(buff.length - 2))
                && a.substring(a.length() - 4).equals(CRC16.check(a.substring(4, a.length() - 4))))) {
            return buff;
        }

        // if ("90-91".equals("" + buffer[0] + buffer[1]) &&
        // (Integer.parseInt("" + buffer[2]) == (buffer.length - 2))) {
        //
        // return buffer;
        // }
        // if (packet.startsWith("sn:")) {
        // return packet.substring(3);
        // }
        return null;
    }

    /**
     * Purpose: 将十六进制的asciii码组成的字符串转换成字符组成的字符串
     *
     * @param s 必须是偶数位
     * @return
     * @throws DecoderException Version: 1.0
     *                          将5a5b 转换成 Z[
     */
    public static String hexToString(String s) throws DecoderException {
        return new String(Hex.decodeHex(s.toCharArray()));
    }

    public static Object parsePacket2Bean(short[] buffer) throws Exception {
        // if(s.length()!=28){
        // throw new Exception("长度不对");
        // }
        AuthMessage bean = new AuthMessage();
        bean.setUnixTimestamp(
                Long.toString(Long.parseLong(toStringHex(buffer[3], buffer[4], buffer[5], buffer[6]), 16)));
        bean.setSn(toStringHex(buffer[8], buffer[9], buffer[10], buffer[11], buffer[12], buffer[13]));
        bean.setTargetSn(toStringHex(buffer[14], buffer[15], buffer[16], buffer[17], buffer[18], buffer[19]));
        bean.setMachineType("" + bean.getSn().charAt(8));// 源 设备类型
        bean.setSequence("" + buffer[20]);
        bean.setMsgType(Type.TypesEnum.fromInt(Integer.valueOf("" + buffer[21])));
        bean.setMsgLength(Long.toString(Long.parseLong(toStringHex(buffer[22]))));

        switch (bean.getMsgType()) {

            case UPLOAD_DATA: {
                bean.setLight(Integer.toString(Integer.valueOf(toStringHex(buffer[23], buffer[24]), 16)));
                bean.setTemperature(Integer.toString(Integer.valueOf(toStringHex(buffer[25], buffer[26]), 16)));
                bean.setHumidity(Integer.toString(Integer.valueOf(toStringHex(buffer[27], buffer[28]), 16)));
                bean.setUvIntensity(Integer.toString(Integer.valueOf(toStringHex(buffer[29], buffer[30]), 16)));
                bean.setParticulate2_5(Integer.toString(Integer.valueOf(toStringHex(buffer[31], buffer[32]), 16)));
                bean.setFormaldehyde(Integer.toString(Integer.valueOf(toStringHex(buffer[33], buffer[34]), 16)));
                break;
            }

            case UPLOAD_STATUS: {

                if (Integer.parseInt(toStringHex(buffer[23], buffer[24]), 16) == (Type.LEVEL1.getType())) {
                    bean.setStatus(Type.LEVEL1);
                }
                if (Integer.parseInt(toStringHex(buffer[23], buffer[24]), 16) == (Type.LEVEL2.getType())) {
                    bean.setStatus(Type.LEVEL2);
                }
                if (Integer.parseInt(toStringHex(buffer[23], buffer[24]), 16) == (Type.LEVEL3.getType())) {
                    bean.setStatus(Type.LEVEL3);
                }
                if (Integer.parseInt(toStringHex(buffer[23], buffer[24]), 16) == (Type.OFF.getType())) {
                    bean.setStatus(Type.OFF);

                }
                break;
            }
            case CONTROL: {

                if (Integer.parseInt(toStringHex(buffer[23], buffer[24]), 16) == (Type.LEVEL1.getType())) {
                    bean.setStatus(Type.LEVEL1);
                }
                if (Integer.parseInt(toStringHex(buffer[23], buffer[24]), 16) == (Type.LEVEL2.getType())) {
                    bean.setStatus(Type.LEVEL2);
                }
                if (Integer.parseInt(toStringHex(buffer[23], buffer[24]), 16) == (Type.LEVEL3.getType())) {
                    bean.setStatus(Type.LEVEL3);
                }
                if (Integer.parseInt(toStringHex(buffer[23], buffer[24]), 16) == (Type.OFF.getType())) {
                    bean.setStatus(Type.OFF);

                }
            }

            case ERROR: {
                //设置新服务器ip端口   手机端与硬件端直连
                break;
            }


            case REMOVE: {
                //解绑    实体无数据处理
                break;
            }

            case SERVER_SETTING: {
                //设置新服务器ip端口   手机端与硬件端直连
                break;
            }


            default:
                break;
        }
        return bean;
    }

    /**
     * Purpose:将各位的十进制数前补0 补足两位
     *
     * @param s
     * @return Version: 1.0
     * @author yxx Create Time: 2015年8月27日 下午4:47:44
     */
    public static Integer complementTo2(short s) {
        return Integer
                .valueOf(String.valueOf("" + s).length() == 1 ? "0" + String.valueOf("" + s) : String.valueOf("" + s));

    }

    /**
     * Purpose:将十进制数转成16进制字符串
     *
     * @param s
     * @return Version: 1.0
     */
    public static String toStringHex(short... s) {
        StringBuilder hex = new StringBuilder();
        for (int i = 0; i < s.length; i++) {
            try {

                hex.append(Integer.toHexString(Integer.valueOf("" + s[i])).length() == 2
                        ? Integer.toHexString(Integer.valueOf("" + s[i]))
                        : "0" + Integer.toHexString(Integer.valueOf("" + s[i])));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return hex.toString().toUpperCase();
    }

    public static short getShort(byte[] b, int index) {
        return (short) (((b[index + 1] << 8) | b[index + 0] & 0xff));
        // return (short) (array[index] << 8 | array[index + 1] & 0xFF);
    }

    public static String toStringHex(String s) {
        byte[] baKeyword = new byte[s.length() / 2];
        for (int i = 0; i < baKeyword.length; i++) {
            try {
                baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            s = new String(baKeyword, "utf-8");// UTF-16le:Not
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return s;
    }

    /**
     * 把16进制字符串转换成字节数组
     *
     * @param hexString
     * @return byte[]
     */
    public static byte[] hexStringToByte(String hexString) {
        int len = (hexString.length() / 2);
        byte[] result = new byte[len];
        char[] achar = hexString.toCharArray();
        for (int i = 0; i < len; i++) {
            int pos = i * 2;
            result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
        }
        return result;
    }

    private static int toByte(char c) {
        byte b = (byte) "0123456789ABCDEF".indexOf(c);
        return b;
    }

}
